package flex.cc.order.manage.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.entity.ServiceProviderDataEntity;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.core.support.BaseController;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.vo.OrderMainVo;
import flex.cc.order.manage.service.DownLoadService;
import flex.cc.order.manage.service.OrderImgService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderManageService;
import flex.cc.order.manage.service.OrderPolicyService;
import flex.cc.order.manage.service.OrderRescueService;
import flex.cc.order.manage.service.OrderTrackService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.vehicle_svr.service.UrgeService;
import flex.cc.vehicle_svr.service.impl.UpPushService;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 服务单操作：派单、催单、拦截取消、改派
 */
@RestController
@RequestMapping(value = "/order/manage")
public class OrderOperationController extends BaseController {
    @Resource
    private OrderManageService orderManageService;
    @Resource
    private OrderMainService orderMainService;
    @Resource
    private UrgeService urgeService;
    @Resource
    private OrderPolicyService orderPolicyService;
    @Resource
    private OrderTrackService orderTrackService;
    @Resource
    private OrderImgService orderImgService;
    @Resource
    private OrderRescueService orderRescueService;
    @Resource
    private DownLoadService downLoadService;
    @Resource
    private ServiceProviderService serviceProviderService;
    @Resource
    private DictCodeService dictCodeService;
    @Resource
	private UpPushService pushService;
   
    /**
	*
	* @author WANGCONG
	* 2021年10月20日下午4:35:12
	* @desc 手动派单
	*/
    @PostMapping(value = "/allotRescue")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "派单")
    public Wrapper<String> allotRescue(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, String> reqVo) {
        logger.info("OrderOperationController -- allotRescue() ====> {}", reqVo);
        Map<String, Object> result = new HashMap<>();
        
        String dataId = reqVo.get("dataId");
        String servicerId = reqVo.get("servicerId"); //服务商Id
        ServiceProviderEntity servicerVo = serviceProviderService.queryById(Integer.valueOf(servicerId));

        /** 2022/02/25 0025 9:31 【2.2-服务包配置需求】 派单前先判断救援商状态是否为启用，若为启用则正常派单，否则返回提示文案：该救援商已禁用，请选择其他救援商 */
        if (!"1".equals(servicerVo.getStatus())) {
            result.put("responseCode", "01");
            result.put("responseMsg", "该救援商已禁用，请选择其他救援商");
            return WrapMapper.ok(JSON.toJSONString(result));
        }

        String publicKey = servicerVo.getPk();
        List<ServiceProviderDataEntity> urlList = serviceProviderService.queryListByYwId(servicerId);
        String createRescue_url = "";
        for(ServiceProviderDataEntity data : urlList){
        	if("1".equals(data.getUrlType())){
        		createRescue_url = data.getUrl();
        	}
        	break;
        }
        if(PublicUtil.isEmpty(createRescue_url)){
        	result.put("responseCode", "01");
            result.put("responseMsg", "未找到服务商下单接口地址");
        }else{
        	List<String> errorOrderNos = new ArrayList<String>();
        	List<String> sameOrderNos = new ArrayList<String>();
        	if (dataId.contains(",")){
        		int successCount = 0;
        		int sameCount = 0;
        		String[] dataIds = dataId.split(",");
        		int total = dataIds.length;
        		for (String currentId: dataIds) {
                    Map<String, Object> allotRescueMap = orderManageService.allotRescue(currentId, createRescue_url, servicerId, publicKey, true);
                    Boolean flag = Boolean.valueOf(allotRescueMap.get("flag").toString());
                    String orderNo = allotRescueMap.get("orderNo").toString();
                    if (!flag){ // 派单异常的服务单
                    	errorOrderNos.add(orderNo);
                    } else {
                    	String sameMsg = allotRescueMap.get("result").toString();
                    	if("服务商一致".equals(sameMsg)){
                    		sameCount++;
                    		sameOrderNos.add(orderNo);
                    	}else{
                    		successCount++;
                    	}
                    }
                }
                if (total == successCount) {
                    result.put("responseCode", "00");
                    result.put("responseMsg", "所选服务单全部派单成功");
                } else {
                    result.put("responseCode", "01");
                    if(sameCount>0){
                    	result.put("responseMsg", "共选中" + total + "个服务单，其中，" + successCount + "个服务单派单成功！派单失败的服务单号为：" + errorOrderNos.toString()
                    		+ "，与原服务商一致的服务单号为："+sameOrderNos.toString());
                    }else{
                    	result.put("responseMsg", "共选中" + total + "个服务单，其中，" + successCount + "个服务单派单成功！派单失败的服务单号为：" + errorOrderNos.toString());
                    }
                }
        	}else { //只勾选了一个服务单
        		Map<String, Object> allotRescueMap = orderManageService.allotRescue(dataId, createRescue_url, servicerId, publicKey, true);
                Boolean flag = Boolean.valueOf(allotRescueMap.get("flag").toString());
                if (flag) {
                	String sameMsg = allotRescueMap.get("result").toString();
                	if("服务商一致".equals(sameMsg)){
                		result.put("responseCode", "01");
                        result.put("responseMsg", "服务单与原服务商一致");
                	}else{
                		result.put("responseCode", "00");
                        result.put("responseMsg", "服务单派单成功");
                	}
                } else {
                    result.put("responseCode", "01");
                    result.put("responseMsg",allotRescueMap.get("result"));
                }
        	}
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }
    
    /**
	*
	* @author R
	* 2022年1月7日上午9:19:19
     * @throws Exception 
	* @desc 拦截取消前对空驶费用校验
	* 空驶费用需判断是否小于【服务类型*设置价格的一半】，如小于提示：“空驶金额小于设置价格的一半
	*/
    @PostMapping(value = "/preCancelRescue")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "拦截取消前校验")
    public Wrapper<String> preCancelRescue(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) throws Exception {
        logger.info("OrderOperationController -- cancelRescue() ====> {}", reqVo);
        Map<String, Object> result = new HashMap<String, Object>();
        if(PublicUtil.isNotEmpty(reqVo.get("dataId"))){
            String dataId = reqVo.get("dataId").toString();
            //空驶费用
            String serviceAmount = reqVo.get("amount").toString();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("dataId", dataId);
            OrderMainEntity orderMainEntity = orderMainService.getOneByParams(params);
            if (PublicUtil.isNotEmpty(orderMainEntity)){
            	//服务类型
            	String serviceItem = orderMainEntity.getServiceItem();
            	//根据对应服务单的服务类型 查询 字典表中对应的价格
            	Map<String, Object> dictParams = new HashMap<>();
    			dictParams.put("typeCode", "serviceItem");
    			dictParams.put("code", serviceItem);
    			DictCodeEntity dictCodeEntity = dictCodeService.getOneByParams(dictParams);
    			try {
    				int standardPrice = Integer.parseInt(dictCodeEntity.getValue1());
    				int amount = Integer.parseInt(serviceAmount);
    				if(amount>(standardPrice/2)){
    					result.put("responseCode", "01");
    	            	result.put("responseMsg", "空驶金额"+amount+"元，大于该类型设置的空驶费用，请确认是否直接提交？");
    				}else if(amount<(standardPrice/2)){
    					result.put("responseCode", "01");
    	            	result.put("responseMsg", "空驶金额"+amount+"元，小于该类型设置的空驶费用，请确认是否直接提交？");
    				}else{
    					result.put("responseCode", "00");
    	            	result.put("responseMsg", "成功");
    				}
    				
				} catch (Exception e) {
					result.put("responseCode", "02");
	            	result.put("responseMsg", "服务类型的设置价格获取异常");
				}
    			
            }else{
            	result.put("responseCode", "02");
            	result.put("responseMsg", "服务单不存在");
            }
        } else {
            result.put("responseCode", "02");
            result.put("responseMsg", "请求参数为空");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }
    
    
    /**
	*
	* @author WANGCONG
	* 2021年10月21日下午5:25:19
     * @throws Exception 
	* @desc 拦截取消
	*/
    @PostMapping(value = "/cancelRescue")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "拦截取消")
    public Wrapper<String> cancelRescue(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) throws Exception {
        logger.info("OrderOperationController -- cancelRescue() ====> {}", reqVo);
        Map<String, Object> result = new HashMap<String, Object>();
        if(PublicUtil.isNotEmpty(reqVo.get("dataId")) && PublicUtil.isNotEmpty(reqVo.get("cancelReason"))){
            String dataId = reqVo.get("dataId").toString();
            //取消备注
            String cancelReason = reqVo.get("cancelReason").toString();
            String servicerId = reqVo.get("servicerId").toString(); //服务商Id，根据它查询服务商的取消接口
            
            //取消状态 1-取消有费用   2-取消无费用
            String cancelType = reqVo.get("cancelType").toString();
            //空驶费用
            String serviceAmount = reqVo.get("amount").toString();
            if(serviceAmount==null||"".equals(serviceAmount)){
            	serviceAmount = "0";
            }
            //空驶距离（单位：公里）  接口需要传的空驶距离单位为米 需转换
            String usedDistance = reqVo.get("distance").toString();
            if(usedDistance==null||"".equals(usedDistance)){
            	usedDistance = "0";
            }else{
            	usedDistance = String.valueOf((int)(Double.parseDouble(usedDistance)*1000));
            }
            //取消状态代码
            String cancelCode = reqVo.get("cancelStatus").toString();
            //预计总行程距离（单位：m）
            String totalDistance = "0";
           
            
            result = orderManageService.cancelRescue(dataId, cancelReason, servicerId,cancelType,serviceAmount,cancelCode,totalDistance,usedDistance);
        } else {
            result.put("responseCode", "01");
            result.put("responseMsg", "请求参数为空");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }
    
    /**
	 *
	 * @author WANGCONG
	 * 2021年9月8日下午4:28:36
	 * @desc 催单动作（页面操作可多选）
	 */
   @PostMapping(value = "/urge")
   @ApiOperation(httpMethod = "POST", value = "催单操作")
   public Wrapper<String> urge(HttpServletRequest request, HttpServletResponse response,@RequestBody OrderMainVo orderMain){
   	Map<String, Object> result = new HashMap<>();
   	System.out.println(orderMain.getUrgeContent());//催单备注
   	String urgeContent = PublicUtil.isNotEmpty(orderMain.getUrgeContent()) ? orderMain.getUrgeContent() : "";
   	String dataIds = orderMain.getUrgeDataIds(); //催单dataId集合
   	System.out.println(dataIds);
   	if(StringUtils.isNotEmpty(dataIds)){
   		orderMain.setDataIdArr(dataIds.split(","));
       }
   	//根据dataId集合查询服务单主表信息
   	List<OrderMainVo> orderList = orderMainService.queryMainByDataIds(orderMain);
   	orderList.forEach(object -> object.setUrgeContent(urgeContent));
   	//add 2021年9月15日10:08:40
   	List<String> errorOrderNos = new ArrayList<String>();
    int successCount = 0;
    int total = orderList.size();
   	for(int i=0; i<orderList.size(); i++){
   		OrderMainVo orderMainVo = orderList.get(i);
   		String orderStatus = orderMainVo.getStatus();
   		if(orderStatus=="00"||orderStatus=="01"||orderStatus=="08"||orderStatus=="09"||orderStatus=="10"||orderStatus=="11"){
   			errorOrderNos.add(orderMainVo.getOrderNo());
   		}else{
   			Map<String, Object> postJson = new HashMap<>();
   	        postJson.put("orderNo", orderMainVo.getOrderNo());
   	        postJson.put("content", urgeContent);
   	        postJson.put("flag", "0"); //1代表上游的，0代表页面操作的
   	        Map<String, Object> resultMap = orderTrackService.urgeOrder(postJson);
   	        String code = (String) resultMap.get("responseCode");
   	        if("01".equals(code)){// 催单失败
   	        	errorOrderNos.add(orderMainVo.getOrderNo());
   	        }else{
   	        	successCount++;
   	        }
   		}
   	}
   	if (total == successCount) {
           result.put("responseCode", "00");
           result.put("responseMsg", "催单成功！");
       } else {
           result.put("responseCode", "01");
           result.put("responseMsg", "共选中" + total + "个服务单，其中，" + successCount
           		+ "个服务单催单成功！催单失败的服务单号为：" + errorOrderNos.toString());
       }
   	return WrapMapper.ok(JSON.toJSONString(result));
   }
   
    /**
	*
	* @author WANGCONG
	* 2021年10月25日下午1:02:28
	* @desc 改派
	*/
    @PostMapping(value = "/changeAllotRescue")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "改派")
    public Wrapper<String> changeAllotRescue(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("OrderOperationController -- changeAllotRescue() ====> {}", reqVo);
        String dataId = PublicUtil.isNotEmpty(reqVo.get("dataIds")) ? reqVo.get("dataIds").toString() : "";
        String servicerId = PublicUtil.isNotEmpty(reqVo.get("servicerId")) ? reqVo.get("servicerId").toString() : "";
        String oldServicerId = PublicUtil.isNotEmpty(reqVo.get("oldServicerId")) ? reqVo.get("oldServicerId").toString() : "";
        Map<String, Object> result = new HashMap<>();
        if(PublicUtil.isNotEmpty(dataId) && PublicUtil.isNotEmpty(servicerId) && PublicUtil.isNotEmpty(oldServicerId)){

            /** 2022/02/25 0025 9:31 【2.2-服务包配置需求】 派单前先判断救援商状态是否为启用，若为启用则正常派单，否则返回提示文案：该救援商已禁用，请选择其他救援商 */
            ServiceProviderEntity servicerVo = serviceProviderService.queryById(Integer.valueOf(servicerId));
            if (!"1".equals(servicerVo.getStatus())) {
                result.put("responseCode", "01");
                result.put("responseMsg", "该救援商已禁用，请选择其他救援商");
                return WrapMapper.ok(JSON.toJSONString(result));
            }

        	result = orderManageService.changeAllotRescue(dataId, servicerId, oldServicerId);
//        	result.put("responseCode", "00");
//            result.put("responseMsg", "改派成功");
        } else {
            result.put("responseCode", "01");
            result.put("responseMsg", "请求参数为空");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }
    
    
    /**
   	*
   	* @author WANGCONG
   	* 2022年2月25日下午15:01:36
   	* @desc 救援单图片回传
   	*/
    @PostMapping(value = "/pushImg/{orderNo}/{sourceName}")
    @ApiOperation(httpMethod = "POST", value = "图片回传操作")
    public Wrapper<String> pushImg(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo, @PathVariable String sourceName){
//    	Map<String, Object> result = new HashMap<>();
//    	result.put("responseCode", "00");
//        result.put("responseMsg", "图片回传成功！");
        Map<String, Object> result = pushService.artificialPushImg(orderNo, sourceName);
    	return WrapMapper.ok(JSON.toJSONString(result));
    }
    
    
}
